<template>
    <div style="display: flex;margin-top: 10px; margin-left:100px; height:1000px;">
        <div style="width: 1000px;  margin-top: 20px;">
            <el-row gutter="2" style=" margin-left: 50px;">
                <el-col :span="24" v-for="(club,index) in clubs" :key="index">
                    <el-card shadow="hover" :body-style="{ padding: '0px' }" style="height:410px; width: 940px; background-color:#fbfbfb; margin-bottom:30px; cursor: pointer;">
                        <el-row>
                            <el-col :span="7">
                                <div style="margin-top: 10px;" >
                                    <el-image style="width: 180px; height: 180px" :src=mainImages[index] :fit="scale" :preview-src-list="[this.mainImages[index]]"></el-image>
                                </div>
                            </el-col>

                            <el-col :span="9">
                                <div  style="margin-top:-6px;margin-left: 20px; font-family: Arial;font-size:16px;font-weight: 350;text-align: left;width:330px">
                                    <p style="height:12px;"><strong>社团名称</strong>：{{club.Cname}}</p>
                                    <p style="height:12px;"><strong>类型</strong>：{{ getTypeText(club.Type) }}</p>
                                    <p style="height:12px;"><strong>所在校区</strong>：{{getAddressText(club.Address)}}</p>
                                    <p style="height:12px;"><strong>级别</strong>：{{getUnitText(club.Unit)}}</p>
                                    <p style="height:12px;"><strong>创建时间</strong>：{{getFormatTime(club.Edate)}}</p>
                                </div>
                            </el-col>

                            <el-col :span="8">
                                <div  style="margin-top:-6px;font-family: Arial;font-size:16px;font-weight: 350;text-align: left">
                                    <p style="height:12px;"><strong>业务指导老师</strong>：{{club.TeacherName}}</p>
                                    <p style="height:12px;"><strong>行政指导老师</strong>：{{club.AdminTeacherName}}</p>
                                    <p style="height:12px;"><strong>社团负责人</strong>：{{club.LeaderName}}</p>
                                    <p style="height:12px;"><strong>联系电话</strong>：{{club.Phone}}</p>
                                    <p style="height:12px;"><strong>联系邮箱</strong>：{{club.Mailbox}}</p>
                                </div>
                            </el-col>

                        </el-row>   
                        <div style="margin-left:-650px;margin-top:30px;height:140px;">
                            <p><img src="../assets/宣传图.png" style="width: 22px; height: 22px; margin-top:2px; vertical-align: middle;" >
                                <button class="btn"><span style="font-size: 15px; font-weight:400;vertical-align: middle;"  onmouseover="this.style.fontSize='14px'" onmouseout="this.style.fontSize='15px'" @click="editMainImage(club.Cid,index)">更换社团宣传图</span></button></p>
                            <el-dialog v-model="IdialogVisible" :modal="false" :before-close="handleClose" style="width:500px; height:280px;  border:0.5px gray ">
                                <el-upload ref="upload" action="#" list-type="picture-card" :limit="1" :file-list="fileList" :auto-upload="false" @preview="handlePictureCardPreview" @remove="handleRemove" :on-exceed="handleExceed" @change="handleChange">
                                    <i style="font-size: 12px;">上传.jpg或.png文件</i>
                                    <div v-for="(file, i) in fileList" :key="i" class="el-upload-list__item">
                                        <img class="el-upload-list__item-thumbnail" :src="file.url"  alt="" >
                                        <span class="el-upload-list__item-actions">
                                            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                                <i class="el-icon-zoom-in"></i>
                                            </span>
                                            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                                                <i class="el-icon-delete"></i>
                                            </span>
                                        </span>
                                    </div>
                                </el-upload>

                                <div style="position: absolute; top: 230px;left: 280px;">
                                    <el-button @click="this.IdialogVisible = false">取消</el-button>
                                    <el-button style="margin-left: 20px" @click="check_load">确认上传</el-button>
                                </div>
                            </el-dialog>

                            <p><img src="../assets/社团图片.png" style="width: 18px; height: 18px;margin-top:2px; vertical-align: middle;" >
                                <button class="btn"><span style="font-size: 15px; font-weight:400;vertical-align: middle;" onmouseover="this.style.fontSize='14px'" onmouseout="this.style.fontSize='15px'" @click="editImages(club.Cid,index)">编辑社团图片</span></button></p>
                            <el-dialog v-model="ImagesdialogVisible" :modal="false" :before-close="HandleClose" style="width:1100px; height:500px;  border:1px solid gray ">
                                <div class="image-container">     
                                    <div v-for="(file, i) in imagesList[this.currentIndex]" :key="i" class="image-item">
                                        <img class="fixed-size-image" :src="file.url"  alt="" >
                                        <div style="margin-top: 10px;">
                                            <span  @click="handlePictureCardPreview(file)">
                                                <el-icon :size="20" ><ZoomIn /></el-icon>
                                            </span>
                                            <span  @click="HandleRemove(file,i)">
                                                <el-icon :size="20" style="margin-left: 30px"><Delete /></el-icon>
                                            </span>
                                        </div>
                                    </div>
                                </div> 

                                <el-upload ref="upload" action="#" list-type="picture-card" :limit="5" :file-list="fileList" :auto-upload="false" @preview="handlePictureCardPreview" @remove="handleremove" :on-exceed="HandleExceed" @change="HandleChange">
                                    <i style="font-size: 12px;">上传.jpg或.png文件</i>
                                    <div v-for="(file, i) in fileList" :key="i" class="el-upload-list__item">
                                        <img class="el-upload-list__item-thumbnail" :src="file.url"  alt="" >
                                        <span class="el-upload-list__item-actions">
                                            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                                <i class="el-icon-zoom-in"></i>
                                            </span>
                                            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleremove(file)">
                                                <i class="el-icon-delete"></i>
                                            </span>
                                        </span>
                                    </div>
                                </el-upload>

                                <div style="position: absolute; top: 450px;left: 580px;">
                                    <el-button @click="reload">取消</el-button>
                                    <el-button style="margin-left: 20px" @click="Check_load">确认上传</el-button>
                                </div>
                            </el-dialog>

                            <el-dialog v-model="DialogVisible">
                                <img width="50%" :src="dialogImageUrl" alt="">
                            </el-dialog>

                            <p><img src="../assets/成员.png" style="width: 18px; height: 18px; vertical-align: middle;">
                                <button class="btn"><span style="font-size: 15px; font-weight:400;vertical-align: middle;" @click="showDialog(club,index)"  onmouseover="this.style.fontSize='14px'" onmouseout="this.style.fontSize='15px'">查看社团成员</span></button></p>
                            <el-dialog v-model="CdialogVisible" width=1100px :modal="false" :before-close="handleClose" style=" height:650px; border: 1px solid gray ">
                                <P style="margin-top: -20px;font-size: 20px;">羽毛球社成员信息</P>
                                <div style="height: 470px;">
                                    <el-table :data="tableData"  ref="multipleTable"  stripe :border="true" max-height="470" style="width: 100%;"  @selection-change="handleSelectionChange">
                                        <el-table-column type="selection" width="55"></el-table-column>
                                        <el-table-column fixed type="index" width="55"></el-table-column>
                                        <el-table-column prop="学工号" label="学工号" width="100" > </el-table-column>
                                        <el-table-column prop="姓名" label="姓名" width="120"> </el-table-column>
                                        <el-table-column prop="性别" label="性别" width="90" :filters="[{text: '男', value: '男'}, {text: '女', value: '女'}]" :filter-method="filterHandler"> </el-table-column>
                                        <el-table-column prop="校区" label="校区" width="100" 
                                        :filters="[{text: '南校区', value: '南校区'}, {text: '北校区', value: '北校区'},{text: '珠海校区', value: '珠海校区'}, {text: '深圳校区', value: '深圳校区'}, {text: '东校区', value: '东校区'},{text: '五校园', value: '五校园'}]" 
                                        :filter-method="filterHandler"></el-table-column>
                                        <el-table-column prop="年级" label="年级" width="100" :filters="[{text: '大一', value: '大一'}, {text: '大二', value: '大二'},{text: '大三', value: '大三'},{text: '大四', value: '大四'},
                                        {text: '研一', value: '研一'},{text: '研二', value: '研二'},{text: '研三', value: '研三'},{text: '硕士', value: '硕士'},{text: '博士', value: '博士'}]" :filter-method="filterHandler">  </el-table-column>
                                        <el-table-column prop="学院" label="学院" width="150"> </el-table-column>
                                        <el-table-column prop="政治面貌" label="政治面貌" width="100" :filters="[{text: '群众', value: '群众'}, {text: '共青团员', value: '共青团员'},{text: '党员', value: '党员'},{text: '其它', value: '其它'}]" :filter-method="filterHandler"> </el-table-column>
                                        <el-table-column prop="邮箱" label="邮箱" width="200"> </el-table-column>
                                        <el-table-column prop="电话" label="电话" width="130"> </el-table-column>
                                        <el-table-column prop="职位" label="职位" width="100"> </el-table-column>
                                    </el-table>
                                </div>
                                <div style="margin-top:30px; margin-left: 700px; display: flex; justify-content: center;">
                                    <el-button @click="this.CdialogVisible = false">取消</el-button>
                                    <el-dropdown style="margin-left: 40px" placement="top">
                                        <el-button type="primary"> 一键导出<i class="el-icon-arrow-down"></i>  </el-button>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                               <el-dropdown-item @click="exportform('csv')">CSV格式</el-dropdown-item>
                                                <el-dropdown-item @click="exportform('excel')">Excel格式</el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                </div>
                            </el-dialog>
                            <div v-if="CdialogVisible" class="Overlay"></div>
                            <p><img src="../assets/活动.png" style="width: 18px; height: 18px;margin-top:2px; vertical-align: middle;" >
                                <button class="btn" @click="this.$router.push('/CreateAct')"><span style="font-size: 15px; font-weight:400;vertical-align: middle;" onmouseover="this.style.fontSize='14px'" onmouseout="this.style.fontSize='15px'">创建活动</span></button></p>
                        </div>
                        <div style="margin-top:-230px; margin-left:294px;font-family: Arial;font-size:16px;font-weight: 350;text-align: left">
                            <p style="height: 15px;" ><strong>社团宗旨：</strong>{{club.Aim}}</p>
                            <p style="height:10px"><strong >社团简介</strong></p>
                            <p style="width: 620px;height:70px;" id="editableIntroduction" contenteditable="true" @input="checkIntroLength(club)">{{club.Introduction}}</p>
                            <p style="height:10px;margin-top: -15px"><strong >社团风采</strong></p>
                            <p style="width: 620px;height:70px; " id="editableOutstanding" contenteditable="true" @input="checkOutstandingLength(club)">{{club.Outstanding}}</p>
                        </div> 
                        <div style="margin-left:800px;margin-top:-15px;">
                            <button style="border: 0;background-color: transparent;"><span style="font-size: 14px; color:hwb(134 15% 75%);text-decoration: underline; text-underline-offset: 0.4em;"
                                 @click="saveChanges(club.Cid)" onmouseover="this.style.fontSize='13px'" onmouseout="this.style.fontSize='14px'">确认修改</span></button>
                        </div>            
                    </el-card>
                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import * as XLSX from 'xlsx';
import { ElMessage } from 'element-plus'

export default {
    data() {
        return { 
            clubs:[],
            mainImages:[],
            images:[],
            clubMembers:[],
            position:[],
            CdialogVisible:false,
            currentClub:{},
            tableData: [],
            multipleSelection: [],
            currentImage:{},
            IdialogVisible:false,
            ImagesdialogVisible:false,
            fileList: [],
            imagesList:[],
            dialogImageUrl: '',
            DialogVisible: false,
            disabled: false,
            currentClubID:'',
            currentIndex:'',
            file:'',
            kind:[],
            returnFileList:[],
            Did:[],
            Ima:[],
            returnfile:[],
            }
    }, 

    methods:{
        showDialog(club,index) {
            this.CdialogVisible = true;
            this.currentClub = club; 
           
            if (this.clubMembers[index] == null){
                  return
              }
            else{   
                this.tableData = this.clubMembers[index].map((member,idx) => {
                let genderString = member.Gender === 0 ? '男' : '女';
                return {
                    学工号:member.UID,
                    姓名: member.Uname,
                    性别: genderString,
                    校区: member.Campus,
                    年级: member.Grade,
                    学院: member.Major,
                    政治面貌: member.PoliticsStatus,
                    邮箱: member.Email,
                    电话: member.Phone,   
                    职位:this.position[index][idx]
                };
            })}
        },

        handleClose(done) {
            done();
        },

        HandleClose(done){
            this.imagesList=this.Ima;
            done();
        },

        exportform(format) {
            const exportData = this.multipleSelection && this.multipleSelection.length > 0 ? this.multipleSelection : this.tableData;

            if (format === 'csv') {
                const csvContent = this.convertToCSV(exportData);
                const filename = '社团成员信息.csv';
                const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });

                if (navigator.msSaveBlob) {
                    navigator.msSaveBlob(blob, filename);
                } else {
                    const link = document.createElement('a');
                    if (link.download !== undefined) {
                        const url = URL.createObjectURL(blob);
                        link.setAttribute('href', url);
                        link.setAttribute('download', filename);
                        link.style.visibility = 'hidden';
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                    }
                }
            } else if (format === 'excel') {
                const wb = XLSX.utils.book_new();
                const ws = XLSX.utils.json_to_sheet(exportData);
                XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
                const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
                const filename = 'Excel导出功能模板.xlsx';
                const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });

                if (navigator.msSaveBlob) {
                    navigator.msSaveBlob(blob, filename);
                } else {
                    const link = document.createElement('a');
                    if (link.download !== undefined) {
                        const url = URL.createObjectURL(blob);
                        link.setAttribute('href', url);
                        link.setAttribute('download', filename);
                        link.style.visibility = 'hidden';
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                    }

                }
            }
        },

        convertToCSV(data) {
            // 将数据转换为 CSV 格式
            const csvRows = [];
            const headers = Object.keys(data[0]);
            csvRows.push(headers.join(','));

            for (const row of data) {
                const values = headers.map(header => {
                    let escaped = ('' + row[header]).replace(/"/g, '\\"');
                    return `"${escaped}"`;
                });
                csvRows.push(values.join(','));
            }

            return csvRows.join('\n');
        },

        handleSelectionChange(val) {
            this.multipleSelection = val;
        },

        filterHandler(value, row, column) {
            const property = column['property'];
            return row[property] === value;
        },

        getFormatTime(time) {
            let date = new Date(time); 
            let year = date.getFullYear();
            let month = (date.getMonth() + 1).toString().padStart(2, '0'); 
            let day = date.getDate().toString().padStart(2, '0');

            return `${year}-${month}-${day}`;
        },

        getUnitText(Unit) {      
            switch (Unit) {
                case '校团委':
                    return '校级';
                default:
                    return '院级';
            }
        },

        getTypeText(type) {
            switch (type) {
                case 1:
                    return '思想政治类';
                case 2:
                    return '学术科技类';
                case 3:
                    return '体育竞技类';
                case 4:
                    return '志愿公益类';
                case 5:
                    return '文化艺术类';
                default:
                    return '';
            }
        },

        getAddressText(address) {  
            switch (address) {
                case 1:
                    return '南校区';
                case 2:
                    return '北校区';
                case 3:
                    return '珠海校区';
                case 4:
                    return '深圳校区';
                case 5:
                    return '东校区';
                case 6:
                    return '五校园'
                default:
                    return '';     
            }
        },

        saveChanges(cid) {
            let introduction = document.getElementById('editableIntroduction').innerText;
            let outstanding = document.getElementById('editableOutstanding').innerText;
   
            if(introduction.length==0||outstanding.length==0){
                ElMessage.warning("内容不能为空")
            }else{
                const formData = new FormData()
                formData.append('cid',cid)
                formData.append('introduction',introduction)
                formData.append('outstanding',outstanding)
                axios. post('/api/club/modifyClubInfo', formData)
                .then(response => {
                    console.log(response)
                    ElMessage.success("修改成功！")
                })
                .catch(error => {
                    console.error(error);
                });
            }
        },

        showMessageBox(message, type) {
            this.$alert(message, '提示', {
            confirmButtonText: '确定',
            type: type,
            });
        },

        checkIntroLength(club) {
            let content = this.$el.querySelector('#editableIntroduction').innerText;
            if (content.length > 110) {
                ElMessage.warning("输入长度过长，请删减！")
                content = content.slice(0,109);
                this.$nextTick(() => {
                    this.$el.querySelector('#editableIntroduction').innerText = content;
                });
                club.Introduction = content;
            }  
        },

        checkOutstandingLength(club) {
            let content = this.$el.querySelector('#editableOutstanding').innerText;
            if (content.length > 110) {
                ElMessage.warning("输入长度过长，请删减！")
                content = content.slice(0,109);
                this.$nextTick(() => {
                    this.$el.querySelector('#editableOutstanding').innerText = content;
                });
                club.Outstanding = content;
            }  
        },

        showcurrentImage(index){
            this.currentImage={0:this.mainImages[index]}
        },

        editMainImage(cid,index){
            this.IdialogVisible=true;
            this.currentClubID =cid;
            this.currentIndex=index;
        },

        editImages(cid,index){
            this.ImagesdialogVisible=true;
            this.currentClubID =cid;
            this.currentIndex=index;
            this.imagesList = this.Ima.slice(); 
        },

        check_load() {
            let file = this.file; 
            if (!file) {
                this.$message.error('请先选择文件');
                return;
            }else{
                const isJPGorPNG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
                if (!isJPGorPNG) {
                    this.$message.error('只能上传 JPG 或 PNG 格式的图片');
                    return;
                }
                if(file.raw.type === 'image/png') this.uploadFile(file,0);
                if(file.raw.type === 'image/jpeg')this.uploadFile(file,1)
            }     
        },

        Check_load() {
            if (this.returnFileList.length==0) {
                this.$message.error('请先选择图片');
                return;
            }else if(this.imagesList[this.currentIndex].length + this.returnFileList.length > 5){
                this.$message.error('1个社团最多只能包含5张图片！');
                return;
            }else{
                for (let i = 0; i < this.returnFileList.length; i++) {  
                    const file = this.returnFileList[i]; 
            
                    const isJPGorPNG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';  
                    if (!isJPGorPNG) {  
                        this.$message.error('只能上传 JPG 或 PNG 格式的图片');   
                        return;  
                    }  
   
                    if (file.raw.type === 'image/jpeg') {
                        this.kind.push(1);
                        this.returnfile.push(file.raw);
                    }
                    else if (file.raw.type === 'image/png')   {
                        this.kind.push(0);
                        this.returnfile.push(file.raw);
                    }         
                }
             }
             this.UploadFile()
        },

        async UploadFile(){
            const formData = new FormData();
            formData.append('uid',this.$store.state.userinfo.account);
            formData.append('cid',this.currentClubID);
            formData.append('deleted',this.Did);
            formData.append('kind',this.kind);
            this.returnfile.forEach((file) => {
                formData.append('returnfile', file);
            });

            await axios.post('/api/club/modifyImages', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
            })
            .then(response=>{
                this.$message.success(`修改成功！`); 
                this.images=response.data.data.images;
                this.Ima=[];
                
                if(this.images!=null){
                    this.images.forEach(imageGroup => {
                        if(imageGroup!=null){
                        let fileListForGroup = imageGroup.map(image => ({
                            url: image.Path,
                            CIid: image.CIid 
                        }));
                        this.Ima.push(fileListForGroup);
                        }
                });}
            
                this.kind=[],
                this.returnFileList=[],
                this.Did=[],
                this.fileList=[],
                this.returnfile=[],
                this.currentIndex='',
                this.ImagesdialogVisible=false
            } )  
            .catch (error=> {
                console.error('Error:', error);
                this.$message.error(`修改失败，请重试！`); 
            })
        },

        async uploadFile(file,kind){
            const formData = new FormData();
            formData.append('cid',this.currentClubID)
            formData.append('file', file.raw);
            formData.append('kind',kind)

            try {
                const response = await axios.post('/api/club/modifyMainImage', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });
                    const newURL =response.data.data.url;
                    this.$message.success(`修改成功！`); 
                    this.mainImages[this.currentIndex]=newURL;
                    this.file='',
                    this.fileList=[],
                    this.currentIndex='',
                    this.currentClubID='',
                    this.ImagesdialogVisible=false
                } catch (error) {
                    console.error('Error:', error);
                    this.$message.error(`修改失败，请重试！`); 
            }
        },

        handleRemove(file) {
            this.fileList = this.fileList.filter(f => f !== file);
        },

        handleremove(file) {
            this.fileList = this.fileList.filter(f => f !== file);
            this.returnFileList =this.returnFileList.filter(f => f!== file);
        },
        
        HandleRemove(file,i) {  
            this.Did.push(this.imagesList[this.currentIndex][i].CIid)
            this.imagesList[this.currentIndex] = this.imagesList[this.currentIndex].filter(f => f !== file)   
        },

        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.DialogVisible = true;
        },

        handleExceed() {
            this.$message.warning(`只能上传1张图片！`);
        },

        HandleExceed() {
            this.$message.warning(`只能包含5张图片！`);
        },

        handleChange(file){
            this.file=file;
        },

        HandleChange(file){
            this.returnFileList.push(file)
        },

        reload(){
            this.ImagesdialogVisible = false;
            this.fileList=[],
            this.imagesList = this.Ima.slice(); 
        }
    },

    mounted() {
        const params = new URLSearchParams();
        params.append('uid', this.$store.state.userinfo.account);

        axios.get('/api/clubManage', { params })
        .then(response => {
            this.clubs = response.data.data.clubs;
            this.images = response.data.data.Images;
            this.mainImages = response.data.data.MainImages;
            this.clubMembers = response.data.data.members;
            this.position = response.data.data.position;
            if(this.images!=null){
            this.images.forEach(imageGroup => {
                if(imageGroup!=null){
                let fileListForGroup = imageGroup.map(image => ({
                    url: image.Path,
                    CIid: image.CIid 
                }));
                this.Ima.push(fileListForGroup);
                }
            });}
        })
        .catch(error => {
            console.error('Error fetching clubManageInfo:', error);
        });
    }
} 
</script>

<style>
.btn{
    border: none;
    cursor: pointer;
    background-color: transparent;
    font-family: Arial;
    font-size:16px;
    color: rgb(64, 62, 56);
    font-weight: 400;
}

.Overlay .el-icon {
    font-size: 20px;
}

.Overlay {
    position: relative;
    top:-148px;
    width:40px;
    height:35px;
    background: rgba(68, 64, 64, 0.5);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: white;
    cursor: pointer;
}

.image-container {
    margin-left:80px;
    display: flex; 
    height: 210px;
    width:900px;
    flex-wrap: nowrap; 
    overflow-x: auto; 
    gap: 50px; 
}

.fixed-size-image {
    width: 140px; 
    height: 140px; 
    object-fit: cover; 
    transition: filter 0.3s ease; 
}

.image-item {
    position: relative;
}

</style>